package cn.kow.kmall.system.service.impl;

import cn.kow.kmall.core.constant.KmallStatusConstant;
import cn.kow.kmall.system.entity.SysNotice;
import cn.kow.kmall.system.repository.SysNoticeRepository;
import cn.kow.kmall.system.service.SysNoticeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: lijun
 * @Description:
 * @Date: Created in 2019-10-29 18:27
 * @Modified By:
 */
@Slf4j
@Service("sysNoticeService")
public class SysNoticeServiceImpl implements SysNoticeService {

    @Autowired
    private SysNoticeRepository sysNoticeRepository;

    @Override
    public void save(SysNotice sysNotice) {
        sysNoticeRepository.create(sysNotice);
    }

    @Override
    public void remove(Long id) {
        sysNoticeRepository.deleteById(id);
    }

    @Override
    public void update(SysNotice sysNotice) {
        sysNoticeRepository.update(sysNotice);
    }

    @Override
    public SysNotice getById(Long id) {
        return sysNoticeRepository.getById(id);
    }

    @Override
    public Page<SysNotice> listByPage(String title, String type, Short status, Pageable pageable) {
        Page<SysNotice> list = sysNoticeRepository.findAll(new Specification<SysNotice>() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (StringUtils.isNotBlank(title)) {
                    predicates.add(criteriaBuilder.like(root.get("noticeTitle"), "%" + title + "%"));
                }
                if (StringUtils.isNotBlank(type)) {
                    predicates.add(criteriaBuilder.equal(root.get("noticeType"), type));
                }
                if (status != null) {
                    predicates.add(criteriaBuilder.in(root.get("status")).value(KmallStatusConstant.NORMAL).value(KmallStatusConstant.DISABLE));
                    predicates.add(criteriaBuilder.equal(root.get("status"), status));
                }
                predicates.add(criteriaBuilder.equal(root.get("deleted"), false));
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        }, pageable);
        return list;
    }
}
